package tech.mobi.child;

import java.util.HashMap;

import tech.mobi.child.base.BaseAct;
import tech.mobi.child.bean.UserInfoBean;
import tech.mobi.child.service.MainService;
import tech.mobi.child.setting.HelpMainAct;
import tech.mobi.child.utils.Configuration;
import tech.mobi.child.utils.DebugUtil;
import tech.mobi.child.utils.Task;
import tech.mobi.child.utils.TaskType;
import tech.mobi.child.utils.Tools;
import tech.mobi.child.utils.UserInfo;
import tech.mobi.child.R;

//import cn.jpush.android.api.JPushInterface;
import com.mobclick.android.MobclickAgent;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.widget.ViewSwitcher;

@SuppressLint("HandlerLeak")
public class PortalAct extends BaseAct {

	private final static int SPLASH_TIME = 3000;// 等待时间

	private static final int MSG_ID_STARTLOGIN = 1;

	//private ProgressDialog progressDialog = null;

	private AnimationDrawable loadingAnimation;
	private ImageView ivLoginLoading;

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_ID_STARTLOGIN:
				Intent intent = new Intent(PortalAct.this, LoginAct.class);
				PortalAct.this.startActivity(intent);
				PortalAct.this.finish();

				break;
			}
			super.handleMessage(msg);
		}

	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		if (!DebugUtil.isDebug()) {
			MobclickAgent.onError(this);// Umeng
		}
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.portal_client);
		ivLoginLoading = (ImageView) this.findViewById(R.id.ivLoginLoading);

	}

	private void loadingData() {
		//loginLoading.setBackgroundResource(R.anim.login_loading); 
		loadingAnimation = (AnimationDrawable) ivLoginLoading.getBackground();
		ivLoginLoading.post(new Runnable()
		 {
			@Override
			public void run()

			{
				loadingAnimation.start();
			}
		});
	}
	
	@Override
	protected void onResume() {
		
		String autoLogin = UserInfo.getAutoLogin(this);
		
		
		loadingData();
		
		// 是否是自动登录，如果是就获取保存的用户名和密码，如果不是自动登录，就转向登录UI
		if (!"".equals(autoLogin) && "yes".equals(autoLogin)) {
//			
			// 是否保存用户名和密码，如果保存，就直接去服务器验证
			String username = UserInfo.getUserName(this);
			String password = UserInfo.getPassword(this);
			if (!("".equals(username)) && !("".equals(password))) {
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("username", username);
				map.put("password", password);
				map.put("flag", Configuration.APP_FLAG);
				map.put("version", Tools.getVersionName(this));
				Task task = new Task(TaskType.TASK_PORTAL_LOGIN, map);
				MainService.newTask(task);
				
//				rlLoading.setVisibility(View.VISIBLE);
				
			} else {
				
				handler.sendEmptyMessageDelayed(MSG_ID_STARTLOGIN, SPLASH_TIME);
			}
		} else {
			handler.sendEmptyMessageDelayed(MSG_ID_STARTLOGIN, SPLASH_TIME);
		}
		super.onResume();
	}

	@Override
	protected void onPause() {
		handler.removeMessages(MSG_ID_STARTLOGIN);
		super.onPause();
	}

	@Override
	public void init() {
		// 启动服务
		if (!MainService.isRunOfService) {
			Intent intent = new Intent(this, MainService.class);
			this.startService(intent);
		}

	}

	@Override
	public void refresh(Object... param) {

		int taskType = (Integer) param[0];
		if (taskType == TaskType.TASK_PORTAL_LOGIN) {
//			if (progressDialog != null && progressDialog.isShowing()) {
//				progressDialog.cancel();
//			}
			
//			ivLoginLoading.setVisibility(View.GONE);
			
			String status = "";
			String message = "";
			UserInfoBean userInfoBean = (UserInfoBean) param[1];
			status = userInfoBean.getStatus();
			message = userInfoBean.getMessage();

			// 验证通过，直接进入主页面
			if (status != null && status.equals(Configuration.EXP_SUCCESS)) {
				
				int iVersion = 0;
				int iVersionCur = 0;
				try {
					iVersionCur = Integer.parseInt(Tools.getVersionName(this)
							.replace(".", ""));
					iVersion = Integer.parseInt(UserInfo.getVersion(this));

				} catch (Exception exx) {
					iVersion = 0;
				}

				if (iVersionCur > iVersion) {
					// 增加新功能提示功能
					Intent intent = new Intent(this, HelpMainAct.class);
					this.startActivity(intent);
				} else {
					Intent intent = new Intent(this, MainAct.class);
					intent.putExtra("flag", "auto");
					this.startActivity(intent);
				}

				/******************************/
				//TODO 将登录用户信息写入内容提供者。
				UserInfo.setUserId(this, userInfoBean.getUserid());
//				UserInfo.setUserName(this, userInfoBean.getUsername());
//				UserInfo.setPassword(this, userInfoBean.getPassword());
				UserInfo.setTrueName(this, userInfoBean.getTurename());
				UserInfo.setUserSex(this, userInfoBean.getUsersex());
				UserInfo.setUserType(this, userInfoBean.getUsertype());
				
				UserInfo.setAutoLogin(this, "yes");
				/******************************/
				
				finish();
			} else {
				Toast.makeText(this, message, Toast.LENGTH_LONG).show();
				handler.sendEmptyMessage(MSG_ID_STARTLOGIN);
			}
		}

	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}


//	/**
//	 * 得到本机电话号码
//	 */
//	private String getPhoneNumber() {
//		String number = null;
//		TelephonyManager telephonyManager = (TelephonyManager) this
//				.getSystemService(Context.TELEPHONY_SERVICE);
//		if (telephonyManager.getSimState() == TelephonyManager.SIM_STATE_READY) {
//			number = telephonyManager.getLine1Number();
//		}
//		return number;
//	}
}